﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using BCGPSRESTful.Controllers;
using BCGPSRESTful.Controllers.Page;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace BCGPSRESTful
{
    /// <summary>
    /// 
    /// </summary>
    public class AddAuthTokenHeaderParameter : IOperationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="context"></param>
        public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }

            var descriptor = context.ApiDescription.ActionDescriptor as ControllerActionDescriptor;

            if (descriptor == null)
            {
                return;
            }

            if (descriptor.ControllerTypeInfo.BaseType == typeof(Controller) || descriptor.ControllerTypeInfo.BaseType == typeof(BCGPSRestfulApiController))
            {
                return;
            }

            bool isAnonymous = descriptor.MethodInfo.GetCustomAttributes(true).Any(p => p is AllowAnonymousAttribute);

            // 非匿名的方法，链接中添加 AccessToken 值
            if (!isAnonymous)
            {
                operation.Parameters.Insert(0, new NonBodyParameter
                {
                    Name = "authorization",
                    In = "header",//query header body path formData
                    Type = "string",
                    Description = "访问令牌。",
                    Required = true //是否必选
                });
            }
            else
            {
                Debug.WriteLine(context.ApiDescription.GroupName + " -> " + context.ApiDescription.ActionDescriptor.DisplayName);
            }
        }
    }
}
